//
//  UIView+STBlockGesture.m
//  STFramework
//
//  Created by jerry on 2019/5/2.
//  Copyright © 2019 jerry. All rights reserved.
//

#import "UIView+STBlockGesture.h"

#import <objc/runtime.h>
static char st_kActionHandlerTapBlockKey;
static char st_kActionHandlerTapGestureKey;
static char st_kActionHandlerLongPressBlockKey;
static char st_kActionHandlerLongPressGestureKey;

@implementation UIView (STBlockGesture)

- (void)st_addTapActionWithBlock:(STGestureActionBlock)block
{
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &st_kActionHandlerTapGestureKey);
    if (!gesture)
    {
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(st_handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &st_kActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &st_kActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}
- (void)st_handleActionForTapGesture:(UITapGestureRecognizer*)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        STGestureActionBlock block = objc_getAssociatedObject(self, &st_kActionHandlerTapBlockKey);
        if (block)
        {
            block(gesture);
        }
    }
}
- (void)st_addLongPressActionWithBlock:(STGestureActionBlock)block
{
    UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &st_kActionHandlerLongPressGestureKey);
    if (!gesture)
    {
        gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(st_handleActionForLongPressGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &st_kActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &st_kActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
}
- (void)st_handleActionForLongPressGesture:(UITapGestureRecognizer*)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        STGestureActionBlock block = objc_getAssociatedObject(self, &st_kActionHandlerLongPressBlockKey);
        if (block)
        {
            block(gesture);
        }
    }
}

@end
